package org.itboys.mobile.controller.mobile;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.service.mongo.front.SundayFrontCollectionService;
import org.itboys.mobile.service.mongo.front.SundayFrontMemberService;
import org.itboys.mobile.service.mysql.front.SundayFrontProductService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.MobileSignUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyang on 2017/12/20.
 * 圣代_收藏_controller_mobile
 */
@Controller
@RequestMapping("/sunday/mobile/collection")
public class SundayMobileCollectionController extends BaseController{

    @Autowired
    private SundayFrontCollectionService collectionService;
    @Autowired
    private SundayFrontProductService productService;
    @Autowired
    private SundayFrontMemberService memberService;


    /**
     * 获取数据
     * @param request
     * @param response
     * @param type  收藏的类型 1商品
     * @param pageSize
     * @param pageNumber
     * @param sort
     * @param order
     */
    @RequestMapping(value="/select", method={ RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】获取收藏数据。商品、关注人、我的店铺")
    public void select(
            HttpServletRequest request,
            HttpServletResponse response,Model model,
            @ApiParam(required=true, name="type", value="收藏的类型 1商品2关注人,3我的店铺（就是产品）。【参与签名】")@RequestParam(value = "type", required = true)Integer type,
            @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
            @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
            @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
            @ApiParam(required = false, name = "order", value = "排序参数。。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
            @ApiParam(value = "随机数。【参与签名】") @RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign){
        try{
            //2018年1月24日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            param.put("type",type);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }

            Long memberId = AccountIdHoldUtils.getMemberId();
            List objects = new ArrayList();
            if(type== SundayCommonConstants.collection_type_product||type== SundayCommonConstants.collection_type_fenxiao){
                objects = productService.getCollection(request,memberId,type);
            }else if(type== SundayCommonConstants.collection_type_member){
                objects = memberService.getCollection(request,memberId);
            }

            ResponseMessage.success(objects);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/collection/select----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 新增收藏
     * @param request
     * @param response
     * @param type  收藏类型 1商品
     * @param otherId   被收藏（商品）的id
     */
    @RequestMapping(value="/save", method={ RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】增加或取消收藏")
    public void save(HttpServletRequest request,
                     HttpServletResponse response,
                     @ApiParam(required=true, name="type", value="收藏类型 1-商品2关注人3-我的店铺（就是产品)。【参与签名】")@RequestParam(value = "type", required = true)Integer type,
                     @ApiParam(required=true, name="otherId", value="被收藏（商品）的id。【参与签名】")@RequestParam(value = "otherId", required = true)Long otherId,
                     @ApiParam(value = "随机数。【参与签名】") @RequestParam(value = "nonce", required = true) String nonce,
                     @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign){
        try{
            //2018年1月16日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            param.put("type",type);
            param.put("otherId",otherId);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            collectionService.saveCollection(memberId,type,otherId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/collection/save----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }


    /**
     * 取消收藏
     * @param request
     * @param response
     * @param type  收藏类型 1商品
     * @param otherIds   被收藏（商品）的ids
     */
    @RequestMapping(value="/delete", method={ RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value="【手机端】删除收藏（支持批量）")
    public void delete(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required=true, name="type", value="收藏类型 1商品2关注人3我的店铺（就是产品)。【参与签名】")@RequestParam(value = "type", required = true)Integer type,
                       @ApiParam(required=true, name="otherIds", value="被收藏（商品）ID的集合，例如：otherIds=1,2,3,4。【参与签名】")@RequestParam(value = "otherIds", required = true)List<Long> otherIds,
                       @ApiParam(value = "随机数。【参与签名】") @RequestParam(value = "nonce", required = true) String nonce,
                       @ApiParam(value = "签名") @RequestParam(value = "sign", required = true) String sign){
        try{
            //2018年1月16日，新增，验证签名
            StringBuilder otherIdsStr = new StringBuilder();
            for(Long otherId : otherIds){
                otherIdsStr.append(otherId+",");
            }
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            param.put("type",type);
            param.put("otherIds",otherIdsStr.substring(0,otherIdsStr.length()-1).toString());
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            collectionService.deleteCollection(memberId,type,otherIds);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/collection/delete----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
}
